package com.ziq.base.utils.permission

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AppOpsManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Process
import android.provider.Settings
import android.view.Gravity
import androidx.core.app.ActivityCompat
import androidx.fragment.app.FragmentActivity
import com.permissionx.guolindev.PermissionX
import com.ziq.base.extension.dp
import java.lang.reflect.InvocationTargetException

class PermissionUtil {
    companion object {
        //定位权限
        var locationPermission = arrayOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )

        fun requestLocationPermission(activity: FragmentActivity, onGrant :(()->Unit)? = null, onReject :(()->Unit)? = null, onRemind :(()->Unit)? = {
            if(!activity.isFinishing){
                val remindPopupWindow = PermissionRemindPopupWindow(activity, "位置权限被禁用", "请到设置中授予获取位置的权限")
                remindPopupWindow.showAtLocation(activity.window.decorView, Gravity.TOP, 0, 50.dp)
            }
        }){
            requestPermission(activity, locationPermission,
                title = "位置权限使用说明",
                content = "用于为您推荐附近的信息，或帮助您在发布的信息中展示位置",
                onGrant = onGrant, onReject = onReject, onRemind = onRemind)
        }

        var permissionPopupWindow: PermissionPopupWindow? = null
        @SuppressLint("CheckResult")
        fun requestPermission(activity: FragmentActivity, permissions: Array<String>, title:String = "", content:String = "", onGrant :(()->Unit)? = null, onReject :(()->Unit)? = null, onRemind :(()->Unit)? = null){
            var allGranted = true
            for (p in permissions) {
                if (!PermissionX.isGranted(activity, p)) {
                    allGranted = false
                }
            }
            if(allGranted){
                onGrant?.invoke()
            } else {
                if(title.isNotEmpty() && content.isNotEmpty()){
                    permissionPopupWindow = PermissionPopupWindow(activity, title, content)
                    try {
                        Handler(activity.mainLooper).postDelayed({
                            if(!activity.isFinishing && permissionPopupWindow != null){
                                permissionPopupWindow?.showAtLocation(activity.window.decorView, Gravity.TOP, 0, 50.dp)
                            }
                        }, 500)
                    }catch (e:Exception){}
                }
                PermissionX.init(activity)
                    .permissions(permissions.toList())
                    .onForwardToSettings { scope, deniedList ->
                        // 用户拒绝了该权限，并且选中『不再询问』，提醒用户手动打开权限
                        onRemind?.invoke()
                    }
                    .request { allGranted, grantedList, deniedList ->
                        permissionPopupWindow?.dismiss()
                        permissionPopupWindow = null
                        if (allGranted) {
                            // 用户已经同意该权限
                            onGrant?.invoke()
                        } else {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            onReject?.invoke()
                        }
                    }
            }


        }




        fun canDrawOverlays(context: Context): Boolean {
            //android 6.0及以上的判断条件
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Settings.canDrawOverlays(context)
            } else checkOp(context, OP_SYSTEM_ALERT_WINDOW)
            //android 4.4~6.0的判断条件
        }

        const val OP_SYSTEM_ALERT_WINDOW = 24
        private fun checkOp(context: Context, op: Int): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                val manager = context.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
                val clazz: Class<*> = AppOpsManager::class.java
                try {
                    val method = clazz.getDeclaredMethod(
                        "checkOp",
                        Int::class.javaPrimitiveType,
                        Int::class.javaPrimitiveType,
                        String::class.java
                    )
                    return AppOpsManager.MODE_ALLOWED == method.invoke(
                        manager,
                        op,
                        Process.myUid(),
                        context.packageName
                    ) as Int
                } catch (e: NoSuchMethodException) {
                    e.printStackTrace()
                } catch (e: IllegalAccessException) {
                    e.printStackTrace()
                } catch (e: InvocationTargetException) {
                    e.printStackTrace()
                }
            }
            return true
        }

        fun requestDrawOverlays(context: Context) {
            val intent = Intent(
                "android.settings.action.MANAGE_OVERLAY_PERMISSION",
                Uri.parse("package:" + context.packageName)
            )
            if (context !is Activity) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            if (intent.resolveActivity(context.packageManager) != null) {
                context.startActivity(intent)
            }
        }
    }

}